<?php
// the base directory of the template version we would like to update people to :)
$sBaseDir="D:/A/webhoneypot/html/../honeypot_data_2";
require_once "$sBaseDir/common_functions.php"; 

if ('cli' == php_sapi_name()) {
	// generate the hashes for the files
	echo "Generating hashes for files...\n";

	$fp = fopen("$sBaseDir/update.txt", 'w+');
	if (!$fp) die_on_error('Failed to open update.txt');
	fwrite($fp, calculate_file_hashes($sBaseDir));
	fclose($fp);
	
	echo "Done!\n"; 
	exit;
}
	
if (!isset($_POST['localfiles']))
	die_on_error('Expected variables not found!');

$aRemoteFiles = parse_update_lines(file_get_contents("$sBaseDir/update.txt"));
if (0 == count($aRemoteFiles))
	die_on_error('No elements found in update.txt!');
	
$aLocalFiles = parse_update_lines($_POST['localfiles']);

$aResult = array();
// add files which have been deleted or changed
foreach($aLocalFiles as $sName => $aDetails) {
	if (isset($aRemoteFiles[$sName])) {
		if ($aDetails['sha1'] != $aRemoteFiles[$sName]['sha1']) {
			add_to_output("- $sName");
			if (is_dir($sBaseDir . '/' . $sName)) {
				add_to_output("+D $sName");
			}
			else {
				add_to_output("+F $sName");
				add_to_output(file_get_contents($sBaseDir . '/' . $sName));
			}			
		}
	}
	else {
		add_to_output("- $sName");
	}
}
// add new files
foreach (array_keys($aRemoteFiles) as $sNewFile) {
	if (isset($aLocalFiles[$sNewFile])) continue;
	if (is_dir($sBaseDir . '/' . $sNewFile)) {
		add_to_output("+D $sNewFile");
	}
	else {
		add_to_output("+F $sNewFile");
		add_to_output(file_get_contents($sBaseDir . '/' . $sNewFile));
	}
}
add_to_output("DONE!");

// add a hass to the end of the message
$sResult = gzcompress(join('', $aResult), 9);
$aResult = null;

$sResult .= sha1($_POST['nonce']
	. 'foo' . 'bar' //TODO: here should be the username and password of the user !!!
	. $sResult); 
print $sResult;
		
function die_on_error($sErrorMsg) {
	if ('cli' == php_sapi_name()) {
		print "ERROR: $sErrorMsg\n";
	}
	else {
		header('HTTP/1.0 404 Not Found');
		print "Error! $sErrorMsg";
	}
	exit;
}

function add_to_output($sLine) {
	global $aResult;
	$aResult[] = sprintf('%x ', strlen($sLine)) . $sLine; 
}